package connections;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import message.StartComunication;

import org.mortbay.util.ajax.Continuation;
import org.mortbay.util.ajax.ContinuationSupport;

import serverDB.Client;
import serverDB.Computer;
import serverDB.ConnectToDataBase;
import serverManger.Server;

/**
 * suspend the client connection 
 * @author ran,barak
 *
 */
public class SuspendServlet extends HttpServlet{
	
	/**
	 * Default serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	private Server server;
	private JettyManager jettyManager;
	private Continuation con;
	private ConnectToDataBase database;
	
	/**
	 * Ctor of SuspendServlet
	 * @param jettyManager
	 */
	public SuspendServlet(JettyManager jettyManager){
		this.jettyManager = jettyManager;
		database = ConnectToDataBase.getInst();
		server=Server.getServerInst();
	}

	/**
	 * get the connection and suspend the client
	 */
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("application/x-java-serialized-object");
		// get the continuation
		con = ContinuationSupport.getContinuation(req, null);
		// open input and output stream
		ObjectInputStream inputStream = new ObjectInputStream(req.getInputStream());
		ObjectOutputStream outputStream = new ObjectOutputStream(resp.getOutputStream());
		try {
			// read object
			StartComunication startCom = (StartComunication)inputStream.readObject();
			inputStream.close();
			// get the client from the DB
			List<Client> client = database.getClient2("from Client where user_name= '"+startCom.getUserName()+"'");//startCom.getUserName(), startCom.getPass());
			Set<Computer> computers = client.get(0).getComputers();
			Computer comp=null;
			// get the computer
			for(Computer c : computers){
				if(c.getComputerName().compareTo(startCom.getComputerName())==0){
					comp=c;
					break;
				}
			}
			if(client!=null){
				// add the user continuation to the hash
				jettyManager.addUserCon(comp.getComputerId(), con);
				server.setClientIsConnected(comp.getComputerId(), false);
				System.out.println("user "+ client.get(0).getUserName()+" registerd");
				// suspend the connection
				con.suspend(0);
				
				outputStream.writeObject(new StartComunication("server","server","server"));
				outputStream.close();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}
}
